package com.hange.excel.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hange.excel.common.BaseResponse;
import com.hange.excel.common.ResultUtils;
import com.hange.excel.model.dto.CellValueDto;
import com.hange.excel.model.dto.CelldataDto;
import com.hange.excel.model.dto.WorkSheetDto;
import com.hange.excel.model.pojo.Celldata;
import com.hange.excel.model.pojo.WorksheetConfig;
import com.hange.excel.service.WorksheetConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * luckysheet接口
 */
@RestController
@RequestMapping("/luckysheet")
public class ExcelController {

    @Autowired
    private WorksheetConfigService worksheetConfigService;

    /**
     * 初始加载
     *
     * @param gridKey 工作簿唯一标识
     * @return
     */
    @PostMapping("/load")
    public String load(String gridKey) {
        List<WorkSheetDto> workSheetDtoList = new ArrayList<>();
        List<WorksheetConfig> worksheetConfigList = worksheetConfigService.getSheetListByWorkId(gridKey);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 工作表
            for (WorksheetConfig w : worksheetConfigList) {
                // 返回前面
                WorkSheetDto workSheetDto = new WorkSheetDto(w.getName(),w.getId(), w.getSheetOrder(), w.getStatus());
                // 拿到所有单元格
                List<Celldata> celldataList = w.getCelldataList();
                if (CollectionUtil.isNotEmpty(celldataList)) {
                    // 用来存放到workSheetDto里面
                    List<CelldataDto> celldataDtoList = new ArrayList<>(celldataList.size());
                    for (Celldata celldata : celldataList) {
                        CelldataDto celldataDto = new CelldataDto();
                        celldataDto.setR(celldata.getRowNum());
                        celldataDto.setC(celldata.getColNum());
                        celldataDto.setV(objectMapper.readValue(celldata.getValue().toString(), CellValueDto.class));
                        celldataDtoList.add(celldataDto); // 添加到新的列表中
                    }
                    workSheetDto.setCelldata(celldataDtoList);
                }
                workSheetDtoList.add(workSheetDto); // 添加到新的列表中
            }
            String s = objectMapper.writeValueAsString(workSheetDtoList);
            return s;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 异步加载其他工作表
     *
     * @param gridKey 唯一标识
     * @param index   工作表的index
     * @return
     */
    @PostMapping("/loadSheetUrl")
    public Object loadSheetUrl(String gridKey, String index) {
        List<WorkSheetDto> workSheetDtoList = new ArrayList<>();
        List<WorksheetConfig> worksheetConfigList = worksheetConfigService.getSheetListByWorkId(gridKey);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 工作表
            for (WorksheetConfig w : worksheetConfigList) {
                // 返回前面
                WorkSheetDto workSheetDto = new WorkSheetDto(w.getName(), w.getId(), w.getSheetOrder(), w.getStatus());
                // 拿到所有单元格
                List<Celldata> celldataList = w.getCelldataList();
                if (CollectionUtil.isNotEmpty(celldataList)) {
                    // 用来存放到workSheetDto里面
                    List<CelldataDto> celldataDtoList = new ArrayList<>(celldataList.size());
                    for (Celldata celldata : celldataList) {
                        CelldataDto celldataDto = new CelldataDto();
                        celldataDto.setR(celldata.getRowNum());
                        celldataDto.setC(celldata.getColNum());
                        celldataDto.setV(objectMapper.readValue(celldata.getValue().toString(), CellValueDto.class));
                        celldataDtoList.add(celldataDto); // 添加到新的列表中
                    }
                    workSheetDto.setCelldata(celldataDtoList);
                }
                workSheetDtoList.add(workSheetDto); // 添加到新的列表中
            }
            String s = objectMapper.writeValueAsString(workSheetDtoList);
            return s;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存
     *
     * @return
     */
    @PostMapping("/save")
    public BaseResponse save(@RequestBody String sheetsData) {
        System.out.println(sheetsData);
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    public ResponseEntity<?> updateSheetData(@RequestBody Map<String, Object> requestBody) {
        // 从请求体中提取参数
        String gridKey = (String) requestBody.get("gridKey");
        String s = (String) requestBody.get("s");
        String t = (String) requestBody.get("t");
        int r = (Integer) requestBody.get("r");
        int c = (Integer) requestBody.get("c");
        Object v = requestBody.get("v");
        // 根据操作类型和目标进行相应的数据库操作
        // 例如，更新数据库中的单元格数据
        if ("change".equals(s) && "cell".equals(t)) {
            // 更新数据库中的单元格数据
            // ...
        }
        // 返回响应给前端
        return ResponseEntity.ok("更新成功");
    }

}
